package com.web.servlet;

import com.domain.User;
import com.service.UserService;
import com.service.impl.UserServiceimol;
import com.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@MultipartConfig
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    //service使用较多,直接定义为成员方法
    private UserService userService = new UserServiceimol();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将编码表放过滤器里
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String action = request.getParameter("action");
        if ("selectAll".equals(action)) {
            selectAll(request, response);
        } else if ("addUser".equals(action)) {
            try {
                addUser(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("toUpdate".equals(action)) {
            toupdate(request, response);
        } else if ("update".equals(action)) {
            try {
                update(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("delete".equals(action)) {
            delete(request, response);
        }else if ("checkName".equals(action)){
            username(request,response);
        }

    }

    private void username(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取数据
        String username = request.getParameter("username");
        System.out.println("username:::"+username);
        //调用service方法,形成布尔类型,返回
        boolean falg=userService.checkname(username);
        System.out.println("falg::::::"+falg);
        //返回
        response.getWriter().write(falg+"");
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取要修改的id
        String id = request.getParameter("id");
        //调用service
        userService.delete(id);
        //重定向
        response.sendRedirect("UserServlet?action=selectAll");
    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException, ServletException {
        //获取session,登录成功的数据
        String good = (String) request.getSession().getAttribute("good");
        if (good==null){
            //请重新登录
            String boss="您还没有登录,先登录,在访问";
            request.getSession().setAttribute("boss",boss);
            //重定向到登录页面
            response.sendRedirect("login.jsp");
            return;
        }
        //获取参数
        //根据id获取以前没有操作过的数据
        User user = userService.getByID(request.getParameter("id"));
        Map<String, String[]> parameterMap = request.getParameterMap();
        BeanUtils.populate(user, parameterMap);
        System.out.println("121311313132:::"+user);
        //通过特定的方法获取使用文件
        Part pic = request.getPart("pic");
        System.out.println("pic::::" + pic);
        //判断是否传输文件
        if (pic.getSize() != 0) {
            System.out.println("++++++++++++++++++++++++++++");
            //获取要传输的文件名文件名
            String submittedFileName = pic.getSubmittedFileName();
            System.out.println(submittedFileName);
            //获取后缀.的索引
            int index = submittedFileName.indexOf(".");
            //截取.后面的形成后缀
            String substring = submittedFileName.substring(index);
            //虚拟路径
            String picpath = "img/" + UUIDUtils.getId() + substring;
            user.setPic(picpath);
            System.out.println(picpath);
            System.out.println("+++++++++++++++++++++++++++++++++++");
            //先获取Context,然后点出来真实路径
            String realPath = request.getServletContext().getRealPath(picpath);
            System.out.println(realPath);
            //2.通过IO操作，将文件数据复制到指定的磁盘位置
            //写到真实路径里
            pic.write(realPath);
        } else {
            System.out.println("+++++++++++++++++++");
            user.setPic(user.getPic());
        }
        //调用service
        userService.update(user);
        //重定向
        response.sendRedirect("UserServlet?action=selectAll");
    }


    //回显修改页面
    private void toupdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单数据id
        String id = request.getParameter("id");
        //根据id获取要修改的对象
        User update = userService.getByID(id);
        //向域中存储数据
        request.setAttribute("update", update);
        //请求转发到update.jsp
        request.getRequestDispatcher("update.jsp").forward(request, response);
    }

    //添加方法
    private void addUser(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException, ServletException {
        //获取session,登录成功的数据
        String good = (String) request.getSession().getAttribute("good");
        if (good==null){
            //请重新登录
            String boss="您还没有登录,先登录,在访问";
            request.getSession().setAttribute("boss",boss);
            //重定向到登录页面
            response.sendRedirect("login.jsp");
            return;
        }

        //获取表单输入的数据
        User user = new User();
        Map<String, String[]> parameterMap = request.getParameterMap();
        BeanUtils.populate(user, parameterMap);
        //通过特定的方法获取使用文件
        Part pic = request.getPart("pic");
        if (pic.getSize()==0){
            //重定向到添加方法
            response.sendRedirect("add.jsp");
            return;
        }else {
            //获取要传输的文件名文件名
            String submittedFileName = pic.getSubmittedFileName();
            System.out.println(submittedFileName);
            //获取后缀.的索引
            int index = submittedFileName.indexOf(".");
            //截取.后面的形成后缀
            String substring = submittedFileName.substring(index);
            //虚拟路径
            String picpath = "img/" + UUIDUtils.getId() + substring;
            System.out.println(picpath);
            user.setPic(picpath);
            //先获取Context,然后点出来真实路径
            String realPath = request.getServletContext().getRealPath(picpath);
            System.out.println(realPath);
            //2.通过IO操作，将文件数据复制到指定的磁盘位置
            //为了避免idea的bug，所以这里对文件输出的文件夹，做一个强制判断
            String dirPath = "/img";
            String dirRealPath = request.getServletContext().getRealPath(dirPath);
            File dir = new File(dirRealPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //写到真实路径里
            pic.write(realPath);
            //调用service方法
            userService.addAll(user);
            //重定向到查看方法
            response.sendRedirect("UserServlet?action=selectAll");
        }
    }

    //查看方法,使用
    private void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取session,登录成功的数据
        String good = (String) request.getSession().getAttribute("good");
        if (good==null){
            //请重新登录
            String boss="您还没有登录,先登录,在访问";
            request.getSession().setAttribute("boss",boss);
            //重定向到登录页面
            response.sendRedirect("login.jsp");
            return;
        }
        //获取表单数据数据
        //调用service方法
        List<User> users = userService.selctAll();
        //向域中存放数据
        request.setAttribute("users", users);
        //重定向或请求转发
        request.getRequestDispatcher("list.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
